var templates = $("#templates");

var wrapperName = $("#name").val();
var edit = $("#edit").val();
var contextPath = $("#contextPath").val();
var wrapper;

function show(json) {
    window.open('', 'showPop', 'width=600,height=450');
    var form = $("<form action='" + contextPath + "/web/ajax/show' target='showPop'  method='POST'/>");
    var data = $("<input name='data' type='hidden' />");
    data.val(json);
    form.append(data);

    form.submit();
}

function test() {
    $.ajax({
	type : "POST",
	contentType : "application/json",
	url : contextPath + "/web/ajax/wrapper-test?test=" + encodeURIComponent($("#testUrl").val()),
	data : JSON.stringify(extractWrapper()),
	dataType : "json"
    }).done(function(data) {
	show(JSON.stringify(data));
    });
}

function save() {
    $.ajax({
	type : "POST",
	contentType : "application/json",
	url : contextPath + "/web/ajax/wrapper-save",
	data : JSON.stringify(extractWrapper()),
	dataType : "json"
    }).done(function(data) {
	if (isNotBlank(data)) {
	    alert(data);
	} else {
	    alert("saved");
	    window.location.href = contextPath + "/web/views/index";
	}

    });
}

function clone(selector) {
    var cont = templates.find(selector).clone(true, true);
    cont.find('.iphone-toggle').iphoneStyle({
	handleMargin : 50
    });
    cont.find(".iPhoneCheckContainer").click(function() {
	var startEnd = $(this).find("input[start-end=true]");
	enableStartEnd(startEnd);
    });

    cont.find("input:checkbox, input:radio, input:file").not('[data-no-uniform="true"],#uniform-is-ajax').uniform();
    cont.removeAttr("id");

    return cont;
}

function extractWrapper() {
    var w = extractFields();
    w.name = $("#name").val();
    w.description = $("#description").val();
    w.base = $("#baseUrl").val();
    w.encoding = $("#encoding").val();

    return w;
}

$(document).ready(function() {

    if (isNotBlank(wrapperName) && edit === "true") {
	$.blockUI({
	    css : {
		border : 'none',
		padding : '15px',
		backgroundColor : '#000',
		'-webkit-border-radius' : '10px',
		'-moz-border-radius' : '10px',
		opacity : .5,
		color : '#fff'
	    }
	});

	$.get(contextPath + "/web/ajax/wrapper-detail/" + wrapperName, function(w) {
	    wrapper = w;
	    if (isNotBlank(wrapper.fields)) {
		$.each(wrapper.fields, function(idx, wrap) {
		    var fieldPattern = addFieldPattern();
		    loadFieldsToPage(wrap, fieldPattern);
		});
	    }
	    $.unblockUI();
	});

    }
});

function fieldTypeSelect(e) {
    var selectedValue = $(e).val();
    var cont = $(e).parents(".control-group").siblings(".fieldTypeCont");

    cont.children().remove();

    var expressionType = clone("#expressionTypeTemplate");
    expressionType.addClass("expressionType");

    var pattern = clone("#patternTemplate");
    pattern.addClass("datePattern");

    switch (selectedValue) {
    case "Date":
	pattern.find("label").html("Date Pattern:");
	cont.append(pattern);
	break;
    case "Custom":
	cont.append(expressionType);
	cont.append("<div class='expressionTypeCont'></div>");
	break;
    }

}

function expressionTypeSelect(e) {
    var selectedValue = $(e).val();
    var cont = $(e).parents(".expressionType").siblings(".expressionTypeCont");

    cont.children().remove();

    var pattern = clone("#patternTemplate");

    var group = clone("#groupTemplate");
    group.addClass("group");

    var inclusive = clone("#inclusiveTemplate");

    var startEnd = clone("#startEndTemplate");
    startEnd.addClass("StartEnd");

    switch (selectedValue) {
    case "Split":
	pattern.find("label.control-label").html("Split Pattern:");
	pattern.addClass("SplitPattern");
	cont.append(pattern);
	break;
    case "StartWith":
	pattern.find("label.control-label").html("Start Pattern:");
	pattern.addClass("StartPattern");
	inclusive.find("label.control-label").html("Start Inclusive:");
	inclusive.addClass("StartInclusive");
	startEnd.find("label.control-label").html("Enable 'EndWith'");
	cont.append(pattern);
	cont.append(inclusive);
	cont.append(startEnd);
	break;
    case "EndWith":
	pattern.find("label.control-label").html("End Pattern:");
	pattern.addClass("EndPattern");
	inclusive.find("label.control-label").html("End Inclusive:");
	inclusive.addClass("EndInclusive");
	startEnd.find("label.control-label").val("Enable 'StartWith'");
	cont.append(pattern);
	cont.append(inclusive);
	cont.append(startEnd);
	break;
    case "RegEx":
	pattern.find("label.control-label").html("RegEx Pattern:");
	pattern.addClass("RegExPattern");
	cont.append(pattern);
	cont.append(group);
	break;
    }
}

function enableStartEnd(e) {

    if (e.length == 0)
	return;

    var isChecked = $(e).is(":checked");
    var selectedValue = $(e).parents(".expressionTypeCont").siblings(".expressionType").find("#expressionType").val();
    var cont = $(e).parents(".expressionTypeCont");

    $(e).parents(".control-group").nextAll().remove();

    var inclusive = clone("#inclusiveTemplate");

    var pattern = clone("#patternTemplate");

    if (isChecked) {
	switch (selectedValue) {
	case "StartWith":
	    pattern.find("label.control-label").html("End Pattern:");
	    pattern.addClass("EndPattern");
	    inclusive.find("label.control-label").html("End Inclusive:");
	    inclusive.addClass("EndInclusive");
	    cont.append(pattern);
	    cont.append(inclusive);
	    break;
	case "EndWith":
	    pattern.find("label.control-label").html("Start Pattern:");
	    pattern.addClass("StartPattern");
	    inclusive.find("label.control-label").html("Start Inclusive:");
	    inclusive.addClass("StartInclusive");
	    cont.append(pattern);
	    cont.append(inclusive);
	    break;
	}
    }
}

function addAttribute(e) {
    $(e).parents(".tag").children(".attributePanel").append(createAttributePattern());
}

function addFieldPattern() {
    var fieldPattern = createFieldPattern();
    $("#fields").append(fieldPattern);
    return fieldPattern;
}

function createFieldPattern() {
    var fieldPattern = clone("#fieldTemplate");
    var unid = Math.floor(Math.random() * 10000000000000001);
    var myTab = unid + "Tab";
    var myTabContent = unid + "TabContent";
    fieldPattern.find("#myTab").attr("id", myTab);
    fieldPattern.find("#myTabContent").attr("id", myTabContent);

    fieldPattern.find("a[href='#local']").attr("href", "#local" + unid);
    fieldPattern.find("a[href='#parent']").attr("href", "#parent" + unid);
    fieldPattern.find("a[href='#pre-sibling']").attr("href", "#pre-sibling" + unid);
    fieldPattern.find("a[href='#next-sibling']").attr("href", "#next-sibling" + unid);
    fieldPattern.find("a[href='#child']").attr("href", "#child" + unid);

    fieldPattern.find("div#local").attr("id", "local" + unid);
    fieldPattern.find("div#parent").attr("id", "parent" + unid);
    fieldPattern.find("div#pre-sibling").attr("id", "pre-sibling" + unid);
    fieldPattern.find("div#next-sibling").attr("id", "next-sibling" + unid);
    fieldPattern.find("div#child").attr("id", "child" + unid);

    fieldPattern.find("#" + myTab + ' a:first').tab('show');
    fieldPattern.find("#" + myTab + ' a').click(function(e) {
	e.preventDefault();
	$(this).tab('show');
    });

    fieldPattern.addClass("fieldPattern");

    fieldPattern.find("h2.fieldNameHeader").html(" <i class='icon-edit'></i> Field Name " + fieldPattern.find("#fieldName").val());
    fieldPattern.find("#fieldName").change(function() {
	fieldPattern.find("h2.fieldNameHeader").html(" <i class='icon-edit'></i> Field Name " + $(this).val());
    });

    var localTag = createTagPattern();
    localTag.find("#tagRecursive").parents(".control-group").remove();
    fieldPattern.find("div[id^='local']").append(localTag);
    fieldPattern.find("div[id^='parent']").append(createTagPattern());
    fieldPattern.find("div[id^='pre-sibling']").append(createTagPattern());
    fieldPattern.find("div[id^='next-sibling']").append(createTagPattern());
    fieldPattern.find("div[id^='child']").append(createTagPattern());

    return fieldPattern;
}

function createTagPattern() {
    var tagPattern = clone("#tagPatternTemplate");
    tagPattern.attr("class", "tag");
    return tagPattern;
}

function createAttributePattern() {
    var attributePanel = clone("#attributeTemplate");
    attributePanel.addClass("attributePattern");

    attributePanel.find("#btnTest a").click(function() {
	$(this).parents(".attributePattern").remove();
    });
    return attributePanel;
}